import axios from 'axios';
import { createStore, applyMiddleware } from 'redux';
import logger  from 'redux-logger'
import thunk from 'redux-thunk'

const initState = {
  list: JSON.parse(localStorage.getItem('list'))  ||[]
}
const rootReducer = (prevState = initState, action) => {
  if(action.type === 'setList') {
    return {
      ...prevState,
      list: action.payload
    }
  }

  return prevState
}

const store = createStore(rootReducer, applyMiddleware(logger, thunk))

store.subscribe(() => {
  const state = store.getState();
  localStorage.setItem('list', JSON.stringify(state.list))
})

export function fetchList() {
  return (dispatch) => {
    axios.get('/api/list').then(resp => {
      dispatch({ type: 'setList', payload: resp.data.data })
    })
  } 
}

export default store